<template>
  <el-dialog
      v-model="isDialogShow"
      title="修改截单时间"
      width="500"
      @closed="handleDialogClosed"
      @open="handleDialogOpen"
  >
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-form-item label="类型" prop="name">
        <span>{{ form.type }}</span>
      </el-form-item>
      <el-form-item label="时间" prop="time">
        <el-time-picker
            v-model="form.time"
            :clearable="false"
            format="HH:mm"
            placeholder="请输入时间"
            value-format="HH:mm"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleConfirmClick">确定</el-button>
        <el-button @click="handleCancelClick">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script lang="ts" setup>
import {ref} from "vue";
import {getDeadlineByMealType, updateDeadlineByMealType} from "@/api/deadline";
import {MealType} from "@/api/types/meal";
import {ElForm, ElMessage} from "element-plus";
import {isAxiosError} from "axios";

const props = defineProps<{ mealType?: MealType }>()
const emit = defineEmits<{
  addSuccess: []
  success: []
  updateSuccess: []
}>()
const isDialogShow = defineModel<boolean>()
const form = ref<{ type?: MealType, time?: string }>({})
const formRef = ref<InstanceType<typeof ElForm>>()
const rules = {
  time: [
    {
      required: true,
      message: "时间不能为空",
      trigger: "blur"
    }
  ]
}

async function getData() {
  if (props.mealType !== undefined) {
    const {result} = await getDeadlineByMealType(props.mealType)
    if (result !== undefined) {
      form.value = {
        type: result[0].type,
        time: `${result[0].hour}:${result[0].minute}`
      }
    }
  }
}

function handleCancelClick() {
  isDialogShow.value = false
}

async function handleConfirmClick() {
  formRef.value?.validate(async (isValid) => {
    if (isValid) {
      try {
        const {result} = await updateDeadlineByMealType({
          type: form.value.type,
          hour: form.value.time?.split(":")[0],
          minute: form.value.time?.split(":")[1]
        })
        if (result === true) {
          ElMessage.success('修改成功');
          emit("updateSuccess")
          emit("success")
          isDialogShow.value = false;
        }
      } catch (error) {
        if (isAxiosError(error) && error.response?.data.message != undefined) {
          ElMessage.error(error.response?.data.message);
        }
      }
    } else {
      ElMessage.error('表单验证失败，请检查输入');
    }
  })
}

async function handleDialogClosed() {
  formRef.value?.resetFields()
}

async function handleDialogOpen() {
  await getData()
}
</script>
